package com.ydc.ln.tutorial.mail.my;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.junit.Test;

/**
 * <pre>
 * 1.Session 
 * 2.Message 
 * 3.Address
 * 4.Authenticator
 * 5.Transport
 * 6.Store and Folder
 * </pre>
 * 
 * @author yangdc
 * 
 */
public class MailDemo {

	public void init() throws MessagingException {
		// Authenticator
		// Authenticator auth = new YourAuthenticator();

		// Session
		Properties props = new Properties();
		// Session session = Session.getDefaultInstance(props, null);
		Session session = Session.getInstance(props, null);
		// Message
		MimeMessage message = new MimeMessage(session);
		message.setContent("Email Content", "text/plain");
		message.setText("Email Content.");
		message.setSubject("subject");
		// Address
		Address address = new InternetAddress("<a href=\"mailto:yangdachao001@163.com\">yangdachao001@163.com</a>");
		// Address address = new InternetAddress("<a href=\"mailto:suixin@asiainfo.com&quot;,&quot;Steve\">suixin@asiainfo.com","Steve</a>");

		message.setFrom(address);
		message.setReplyTo(new Address[] { address });

		// Message.RecipientType 。
		// message.addRecipient(type,address);
		// Message.RecipientType有几个预先定义好的类型
		// Message.RecipientType.TO 收件人
		// Message.RecipientType.CC 抄送
		// Message.RecipientType.BCC 暗送

		// Address toAddress = new InternetAddress("<a href="mailto:teacher@17288.com">teacher@17288.com</a>");
		// Address[] ccAddress = {new InternetAddress("<a href="mailto:schoolmate1@17288.com&quot;),new">schoolmate1@17288.com"),new</a> InternetAddress("<a
		// href="mailto:schoolmate2@17288.com">schoolmate2@17288.com</a>")};
		// message.addRecipient(Message.RecipientType.To, toAddress);
		// message.addRecipient(Message.RecipientType.CC, ccAddress);

		// Transport
		Transport.send(message);

		// Transport transport = session.getTransport("smtp");
		// transport.sendMessage(message, message.getAllRecipients());
		// transport.close();

		// Store and Folder
		Store store = session.getStore("pop3");
		// store.connect(host, username, password);
		Folder folder = store.getFolder("INBOX");
		folder.open(Folder.READ_ONLY);
		// Message message[] = folder.getMessages();
	}

	@Test
	public void testSendEmail () {
		Map<String, String> data = new HashMap<String, String>();
		boolean flag = sendEmail(data);
		org.junit.Assert.assertTrue(flag);
		
	}
	
	public boolean sendEmail(Map<String, String> data) {
		// 创建Properties 对象
		Properties props = System.getProperties();
		props.put("mail.smtp.host", Constants.HOST); // 全局变量
		props.put("mail.smtp.auth", "true");

		// 创建邮件会话
		Session session = Session.getDefaultInstance(props, new Authenticator() { // 验账账户
					@Override
					public PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(Constants.USERNAME, Constants.PASSWORD);
					}
				});

		try {
			// 定义邮件信息
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(Constants.FROM));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
			// 这里可以添加多个目的用户
					data.get(Constants.EMAIL_TO)));
			// 添加邮件发送时间（不知道体现在哪儿）
			message.setSentDate(new Date());
			// 要编码，否则中文会出乱码，貌似这个方法是对数据进行了
			// ("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=")形势的包装
			message.setSubject(MimeUtility.encodeText(data.get(Constants.EMAIL_SUBJECT), "gbk", "B"));

			MimeMultipart mmp = new MimeMultipart();
			MimeBodyPart mbp_text = new MimeBodyPart();
			// "text/plain"是文本型，没有样式，
			// "text/html"是html样式，可以解析html标签
			mbp_text.setContent(data.get(Constants.EMAIL_TEXT), "text/html;charset=gbk");
			mmp.addBodyPart(mbp_text); // 加入邮件正文

			// 处理附件，可以添加多个附件
			if (data.get(Constants.EMAIL_ATTACHMENT) != null) {
				String[] files = data.get(Constants.EMAIL_ATTACHMENT).split(",");
				if (files.length != 0) {
					for (String file : files) {
						MimeBodyPart mbp_file = new MimeBodyPart();
						FileDataSource fds = new FileDataSource(file);
						mbp_file.setDataHandler(new DataHandler(fds));
						mbp_file.setFileName(MimeUtility.encodeText(fds.getName(), "gbk", "B"));
						mmp.addBodyPart(mbp_file);
					}
				}
			}
			message.setContent(mmp);
			// message.setText(data.get(Constants.EMAIL_TEXT));

			// 发送消息
			// session.getTransport("smtp").send(message); //也可以这样创建Transport对象
			Transport.send(message);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	class Constants {

		public static final String HOST = "smtp.163.com";
		public static final String USERNAME = "yangdachao001@163.com";
		public static final String PASSWORD = "nokia2009!#@";
		public static final String FROM = "yangdachao001@163.com";
		public static final String EMAIL_TO = "yangdachao001@163.com";
		public static final String EMAIL_SUBJECT = "email_subject";
		public static final String EMAIL_TEXT = "email_text";
		public static final String EMAIL_ATTACHMENT = "email_attachment";
		
		Map<String, String> data = new HashMap<String, String>();
		
	}
}
